package springboot.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.web.server.ConfigurableWebServerFactory;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
	@Bean
	public ShiroFilterFactoryBean shiroFilterFactoryBean
					(@Qualifier("getDefaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager) {
		ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
		bean.setSecurityManager(defaultWebSecurityManager);
		
		Map<String, String> filterMap = new LinkedHashMap<>();
		/*
		 * anon：无需认证访问
		 * authc：必须认证访问
		 * user：必须拥有 记住我 功能访问
		 * perms：拥有对某资源的权限
		 * role：拥有某个角色权限
		 * */
		
		filterMap.put("/static/**", "anon");
		filterMap.put("/image/**", "anon");//img
		filterMap.put("/css/**", "anon");//css
		filterMap.put("/js/**", "anon");//js


//  filterMap.put("/**", "anon");
		filterMap.put("/", "authc,user");
		
		// 配置退出 过滤器,其中的具体地退出代码Shiro已经替我们实现了
		filterMap.put("/logout", "logout");
		
		bean.setFilterChainDefinitionMap(filterMap);
		bean.setLoginUrl("/login");//拦截未登录，跳转页面
		bean.setUnauthorizedUrl("/login");//未授权页面
		bean.setSuccessUrl("/");
		return bean;
	}
	
	
	@Bean
	public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
		
		DefaultWebSecurityManager SecurityManager = new DefaultWebSecurityManager();
		
		SecurityManager.setRealm(userRealm);
		return SecurityManager;
	}
	
	@Bean
	public UserRealm userRealm() {
		return new UserRealm();
	}
	
	@Bean
	public ShiroDialect getShiroDialect() {
		return new ShiroDialect();
	}
	
	@Bean
	public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer() {
		return factory -> {
			ErrorPage error401Page = new ErrorPage(HttpStatus.UNAUTHORIZED, "/unauthorized");
			ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/404");
			ErrorPage error500Page = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/500");
			factory.addErrorPages(error401Page, error404Page, error500Page);
		};
	}
	
	
}
